<template>
  <div class="equipment-archive">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="设备编号">
          <el-input v-model="searchForm.deviceNo" placeholder="请输入设备编号" clearable />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.deviceName" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="searchForm.deviceType" placeholder="请选择设备类型" clearable>
            <el-option 
              v-for="item in deviceTypeList" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="searchForm.status" placeholder="请选择设备状态" clearable>
            <el-option 
              v-for="item in deviceStatusList" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新增设备</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="deviceNo" label="设备编号" width="150" />
        <el-table-column prop="deviceName" label="设备名称" min-width="200" />
        <el-table-column prop="deviceTypeName" label="设备类型" width="120" />
        <el-table-column prop="deviceModel" label="设备型号" width="150" />
        <el-table-column prop="manufacturer" label="生产厂家" width="200" />
        <el-table-column prop="purchasePrice" label="购买价格" width="120">
          <template #default="scope">
            {{ formatPrice(scope.row.purchasePrice) }}
          </template>
        </el-table-column>
        <el-table-column prop="statusName" label="设备状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="设备位置" width="150" />
        <el-table-column prop="responsiblePerson" label="负责人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="form.deviceType" placeholder="请选择设备类型" style="width: 100%">
                <el-option 
                  v-for="item in deviceTypeList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备型号">
              <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备规格">
              <el-input v-model="form.deviceSpec" placeholder="请输入设备规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产厂家">
              <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买日期">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                placeholder="请选择购买日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买价格">
              <el-input-number
                v-model="form.purchasePrice"
                :precision="2"
                :step="100"
                :min="0"
                style="width: 100%"
                placeholder="请输入购买价格"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备位置">
              <el-input v-model="form.location" placeholder="请输入设备位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-input v-model="form.responsiblePerson" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态">
              <el-select v-model="form.status" placeholder="请选择设备状态" style="width: 100%">
                <el-option 
                  v-for="item in deviceStatusList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="设备描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入设备描述"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="设备详情"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="deviceDetail" class="device-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备编号">{{ deviceDetail.deviceNo }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ deviceDetail.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ deviceDetail.deviceTypeName }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{ deviceDetail.deviceModel || '无' }}</el-descriptions-item>
          <el-descriptions-item label="设备规格">{{ deviceDetail.deviceSpec || '无' }}</el-descriptions-item>
          <el-descriptions-item label="生产厂家">{{ deviceDetail.manufacturer || '无' }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ deviceDetail.supplier || '无' }}</el-descriptions-item>
          <el-descriptions-item label="购买日期">{{ formatDate(deviceDetail.purchaseDate) }}</el-descriptions-item>
          <el-descriptions-item label="购买价格">{{ formatPrice(deviceDetail.purchasePrice) }}</el-descriptions-item>
          <el-descriptions-item label="设备状态">
            <el-tag :type="getStatusTagType(deviceDetail.status)">
              {{ deviceDetail.statusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="设备位置">{{ deviceDetail.location || '无' }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ deviceDetail.responsiblePerson || '无' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ deviceDetail.contactPhone || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(deviceDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="设备描述" :span="2">{{ deviceDetail.description || '无' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ deviceDetail.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { equipmentApi } from '@/api/equipment/equipment'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "equipment_archive",
  data() {
    return {
      // 搜索表单
      searchForm: {
        deviceNo: '',
        deviceName: '',
        deviceType: '',
        status: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 表单数据
      form: {
        deviceName: '',
        deviceType: '',
        deviceModel: '',
        deviceSpec: '',
        manufacturer: '',
        supplier: '',
        purchaseDate: '',
        purchasePrice: null,
        status: 0,
        location: '',
        responsiblePerson: '',
        contactPhone: '',
        description: '',
        remark: ''
      },
      // 表单验证规则
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        deviceType: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ]
      },
      // 表单引用
      formRef: null,
      // 编辑模式
      isEdit: false,
      // 编辑的设备ID
      editId: null,
      // 详情对话框
      detailDialogVisible: false,
      // 设备详情数据
      deviceDetail: null,
      // 设备类型列表
      deviceTypeList: [],
      // 设备状态列表
      deviceStatusList: []
    }
  },
  mounted() {
    this.loadTableData()
    this.loadDeviceTypeList()
    this.loadDeviceStatusList()
  },
  methods: {
    // 加载表格数据
    async loadTableData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          current: this.pagination.current,
          size: this.pagination.size
        }
        const res = await equipmentApi.getDevicePage(params)
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        }
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 加载设备类型列表
    async loadDeviceTypeList() {
      try {
        const res = await equipmentApi.getDeviceTypeList()
        if (res.code === 200) {
          this.deviceTypeList = res.data
        }
      } catch (error) {
        console.error('加载设备类型列表失败:', error)
      }
    },

    // 加载设备状态列表
    async loadDeviceStatusList() {
      try {
        const res = await equipmentApi.getDeviceStatusList()
        if (res.code === 200) {
          this.deviceStatusList = res.data
        }
      } catch (error) {
        console.error('加载设备状态列表失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadTableData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        deviceNo: '',
        deviceName: '',
        deviceType: '',
        status: ''
      }
      this.handleSearch()
    },

    // 新增设备
    handleAdd() {
      this.isEdit = false
      this.editId = null
      this.dialogTitle = '新增设备'
      this.form = {
        deviceName: '',
        deviceType: '',
        deviceModel: '',
        deviceSpec: '',
        manufacturer: '',
        supplier: '',
        purchaseDate: '',
        purchasePrice: null,
        status: 0,
        location: '',
        responsiblePerson: '',
        contactPhone: '',
        description: '',
        remark: ''
      }
      this.dialogVisible = true
    },

    // 编辑设备
    handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogTitle = '编辑设备'
      this.form = {
        deviceName: row.deviceName,
        deviceType: row.deviceType,
        deviceModel: row.deviceModel,
        deviceSpec: row.deviceSpec,
        manufacturer: row.manufacturer,
        supplier: row.supplier,
        purchaseDate: row.purchaseDate,
        purchasePrice: row.purchasePrice,
        status: row.status,
        location: row.location,
        responsiblePerson: row.responsiblePerson,
        contactPhone: row.contactPhone,
        description: row.description,
        remark: row.remark
      }
      this.dialogVisible = true
    },

    // 保存设备
    async handleSave() {
      try {
        await this.$refs.formRef.validate()
        
        if (this.isEdit) {
          // 编辑
          const res = await equipmentApi.updateDevice(this.editId, this.form)
          if (res.code === 200) {
            ElMessage.success('设备更新成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          // 新增
          const res = await equipmentApi.addDevice(this.form)
          if (res.code === 200) {
            ElMessage.success('设备创建成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    // 查看详情
    async handleView(row) {
      try {
        const res = await equipmentApi.getDeviceById(row.id)
        if (res.code === 200) {
          this.deviceDetail = res.data
          this.detailDialogVisible = true
        } else {
          ElMessage.error(res.message || '获取设备详情失败')
        }
      } catch (error) {
        console.error('获取设备详情失败:', error)
        ElMessage.error('获取设备详情失败')
      }
    },

    // 删除设备
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm('确定要删除该设备吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await equipmentApi.deleteDevice(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadTableData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadTableData()
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
    },

    // 格式化价格
    formatPrice(price) {
      if (!price) return '0.00'
      return Number(price).toFixed(2)
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case 0:
          return 'info'
        case 1:
          return 'success'
        case 2:
          return 'warning'
        case 3:
          return 'danger'
        default:
          return 'info'
      }
    }
  }
}
</script>

<style scoped>
.equipment-archive {
  padding: 20px;
}

.search-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.device-detail .el-descriptions {
  margin-bottom: 20px;
}
</style>
